<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Time</title>
  <style>
    .timeDiv{
      margin: 0px auto;
      width: 500px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      background-color: yellow;
      color: tomato;
      border: 1px solid red;
      font-size: 26px;
      font-weight: bold;
    }
  </style>
</head>
<body onload="loadTime()">
<div id="timer" class="timeDiv"></div>


<button onclick="formatTime(new Date())">测试</button>
<script>


  function loadTime(){
    //创建日期时间对象
    let time = new Date();

    document.getElementById("timer").innerHTML=formatTime(time);
    //延时器,延迟等待指定的时间后调用指定的函数
    setTimeout(loadTime,1000);
  }
  /*
      格式化时间
  */
  function formatTime(time){
    let year = time.getFullYear();//获得年
    let month = fillZear(time.getMonth()+1);//获得月(默认月从0开始)
    let day = fillZear(time.getDate());//获得日
    let hour = fillZear(time.getHours());//获得小时
    let min = fillZear(time.getMinutes());//获得分钟
    let second = fillZear(time.getSeconds());//获得秒
    let timeStr = year+"-"+month+"-"+day+" "+hour+":"+min+":"+second;
    return timeStr;
  }

  /*
  填充零
  */
  function fillZear(num){
    if(num<10){
      return "0"+num;
    }
    return num;
  }
</script>
</body>
</html>